import React, { Component, createRef } from 'react';

// 
import store from '../../homeworkstore/index'
// 导入同异步任务
import { setschoolarrAsyncFn, delSchoolFn } from '../../homeworkstore/actions/actions'

// 导入模态款组件
import Modal from './Modal';
class Mycls extends Component {
    constructor() {
        super()
        this.state = {
            isshow: false,
            schoolArr: store.getState(),
            item: '',  // 学校的名称
            flag: true,  // 默认添加按钮显示
        }
        // 重新订阅store数据
        store.subscribe(() => {
            this.setState(() => ({ schoolArr: store.getState() }))
        })
    }
    ref1 = createRef();
    render() {
        const { schoolArr, isshow } = this.state;
        console.log(schoolArr);
        return (
            <div>
                <p><button onClick={() => this.addschool()}>添加学校</button></p>
                <ul>
                    {
                        schoolArr.schoolArr.map((item) => <li key={item.id}>
                            <span>{item.id}</span>
                            <span>{item.school_name}</span>
                            <button onClick={() => this.delFn(item.id)}>删除</button>
                            <button onClick={() => this.editFn1(item)}>编辑</button>
                        </li>)
                    }
                </ul>
                {/* 显示模态框组件 */}
                {
                    isshow ? <Modal ref={this.ref1} hideFn={this.hideFn} flag={this.state.flag} item={this.state.item}></Modal> : <></>
                }

            </div>
        );
    };
    componentDidMount() {
        store.dispatch(setschoolarrAsyncFn())
    }
    // 定义添加学校方法
    addschool() {
        console.log(this);
        // 显示模态框
        this.setState({
            isshow: true,
            flag: true
        })

    };
    delFn = (id) => {
        // 派发删除任务
        store.dispatch(delSchoolFn(id))
    };
    editFn1(item) {
        // 显示模态框
        this.setState({
            isshow: true,
            item,
            flag: false
        }, () => {
            console.log(this.ref1);
            this.ref1.current.backeditFn()
        })
        //如何获取的name 交给model 组件进行数据的回填?
        // console.log('name', name);
        // 获取子组件的实例对象
        // console.log(this.ref1);

    };
    hideFn = () => {
        this.setState({
            isshow: false
        })
    }
}

export default Mycls;
